<?php
namespace Home\Controller;

use Think\Controller;

/**
*@desc 普通用户后台
*/
class UserController extends CommonController {
    private $auth_status = 0;//默认：未认证
    private $user_email = null;//用户邮箱
    private $uid = null;
    private $user_token = null;
    private $apis_table = "dmp_service_apis_image";//api信息 镜像表
    // private $api_auth_record_table = "dmp_service_authorization_record";//api审核记录表
    private $api_auth_record_table = "dmp_orders";//用户订单表
    private $auth_type = 1;

    public function __construct(){
        parent::__construct();
        //是否普通用户，且是登录状态
        
        $this->getAuthStatus();
        $this->auth_status = session('37degree_auth_status');
        
        $this->user_email = session('user_email');
        $this->assign('user_email',$this->user_email);
        $this->uid = session('uid');
        $this->user_token = session('user_token');
        $this->auth_type = session('auth_type');

        $this->assign('user_token',$this->user_token);

        if(empty($this->uid)) redirect('/member/login.html');

    }

    //默认页
    public function index(){
        $this->assign('auth_user_status',$this->auth_status);
        $this->assign('user_auth_fail',session('user_auth_fail'));
        $this->assign('auth_type',$this->auth_type);

       //如果是服务商跳转到服务商用户基本信息页
       // if($this->role==2){
       //  	redirect('/apiworks/userinfo');
       //  }

        //登录时没有认证
        if(empty(session('user_name')) || session('user_name')=='Guest'){
            $userModel = M('Users');
            $user_where['id'] = $this->uid;
            $user_info = $userModel->where($user_where)->find();
            //个人认证
            $name = $user_info['user_name'];
            //个人认证及认证完成时，用户姓名信息
            if($this->auth_type==2){//企业认证，需要获取企业名称
                $enterprise_id = session('enterprise_id');
                $enterpriseModel = M('Enterprises');
                $where['id'] = $enterprise_id;
                $enterprise_info = $enterpriseModel->where($where)->find();
                if(!empty($enterprise_info)) $name = $enterprise_info['enterprise_name'];
            }
        }else{
            $name = session('user_name');
        }

        $this->assign('name',$name);
        $this->assign('head_title',"帐号信息－云途数据市场");
        $this->display();
    }

	/**
	* @desc 认证
	*/
    public function auth(){
        if(IS_POST){
            $auth_type = I('post.auth_type',1);
            $data = I('post.');
            
            if($auth_type==1){
                //个人用户认证
                $this->addUserAuth($data);

            }else if($auth_type==2){
                //企业用户认证
                $this->addEnterpriseAuth($data);
            }

            //通讯大后台，token有效期修改(*****************审核通过后才执行*********************)
            //todo
            
        }else{
            if(empty($this->uid)) redirect('/member/login.html');
            //已认证
            if($this->auth_status==1 || $this->auth_status == 2){
                redirect('/user/index.html');
            }else{
                //读取该用户已有认证信息
                if($this->auth_status==3){//提交待审核or审核失败
                    $userModel = M();
                    if($this->auth_type==2){
                        $sql = "select u.auth_type,e.* from dmp_users u left join dmp_enterprises e on e.id=u.enterprise_id where u.id=".(int) $this->uid;
                        $auth_id = session('enterprise_id');
                    }else{
                        $sql = "select u.* from dmp_users u where u.id=".(int) $this->uid;
                        $auth_id = $this->uid;
                    }
                    $info = $userModel->query($sql);

                    if(!empty($info)){
                        $this->assign('info',$info[0]);
                        $this->assign('auth_id',$auth_id);
                    }
                }
                $this->assign('head_title','帐号认证－云途数据市场');
                $this->display('auth');   
            }
        }
    }

    //修改密码
    public function resetpasswd(){
        if(IS_POST){
            $old_passwd = trim( I('post.old_passwd',null) );
            $new_first_pwd = trim( I('post.new_first_pwd',null) );
            $new_second_pwd = trim ( I('post.new_second_pwd',null) );
            //echo "<pre>";print_r($_POST);DIE;
            if(empty($old_passwd)){
                $this->ajaxReturn( array('status'=>1,'msg'=>'请输入密码','data'=>null) );
            }
            
            //判断密码规则
            if(!checkPasswd($old_passwd)){
                $this->ajaxReturn( array('status'=>1,'msg'=>'请输入正确的密码','data'=>'src') );
            }
            
            if(empty($new_first_pwd)){
                $this->ajaxReturn( array('status'=>2,'msg'=>'请输入密码','data'=>null) );
            }
            if(empty($new_second_pwd)){
                $this->ajaxReturn( array('status'=>3,'msg'=>'请输入密码','data'=>null) );
            }           
            
           
            if($old_passwd == $new_first_pwd){
                $this->ajaxReturn( array('status'=>1004,'msg'=>'原密码与新密码不能一样','data'=>null) );
            }
            if($new_second_pwd != $new_first_pwd){
                $this->ajaxReturn( array('status'=>3,'msg'=>'请输入相同的密码','data'=>'new2') );
            }
            
            //判断密码规则
            if(!checkPasswd($new_first_pwd)){
                $this->ajaxReturn( array('status'=>2,'msg'=>'请输入正确的密码','data'=>'new1') );
            }
            
            $user = M('Users');
            $where['user_email'] = $this->user_email;
            $user_info = $user->where($where)->find();
            if(!empty($user_info)){
                if(md5($old_passwd) == $user_info['user_passwd']){
                    $data['user_passwd'] = md5($new_first_pwd);
                    $result = $user->where($where)->save($data);
                    if($result){
                        $this->ajaxReturn( array('status'=>200,'msg'=>'密码修改成功','data'=>true) );
                    }else{
                        $this->ajaxReturn( array('status'=>1005,'msg'=>'修改密码失败','data'=>NULL) );
                    }
                }else{
                    //请输入正确原始密码
                    $this->ajaxReturn( array('status'=>1,'msg'=>'请输入正确的密码','data'=>null) );
                }
            }else{
                //需要重新登录
                $this->ajaxReturn( array('status'=>1010,'msg'=>'请重新登录','data'=>null) );
            }

        }else{
        	$this->assign('head_title','修改密码－云途数据市场');
            $this->display();
        }
        
    }

    //授权
    public function apiAuth(){
        //用户信息

        //授权api信息

        //通知大后台
        
    }

    //我的数据
    public function mlist(){
        if(empty($this->uid)) redirect('/member/login.html');
        $apisModel = M();

        //获取用户所有申请的服务及api信息
        $api_sql = "select apis.api_id,apis.api_name,apis.api_name_en,apis.service_id,apis.api_status,apis.service_name_en,re.pay_status,apis.api_is_charge from ".$this->api_auth_record_table." re left join ".$this->apis_table." apis on apis.api_id=re.api_id where re.user_id=".$this->uid." and re.enable=1 and re.pay_status >0 ";
        $api_sql.= " order by apis.api_name ";
        
        $api_list = $apisModel->query($api_sql);
        $api_name_en_array = $api_data = $api_to_gateway_array = array();

        if(!empty($api_list)){
            foreach ($api_list as $ak=>$av){
                if($av['api_name_en']){
                    array_push($api_name_en_array, "'".$av['api_name_en']."'");
                    $api_data[$av['api_name_en']] = $av;
                    $api_data[$av['api_name_en']]['cnt_ret'] = $api_data[$av['api_name_en']]['cnt_call'] = $api_data[$av['api_name_en']]['cnt'] = 0;
                    
                    if($av['api_is_charge']==0){
                        $api_data[$av['api_name_en']]['rest_call'] = "无限次";
                        $api_data[$av['api_name_en']]['rest_time'] = -1;
                    }else{
                        $api_data[$av['api_name_en']]['rest_call'] = $api_data[$av['api_name_en']]['rest_time'] = 0;    
                    }
                    

                    //通过网关获取，api使用情况的api列表
                    if($av['api_is_charge']){
                        $api_to_gateway_array[] = array(
                            'user'=>$this->user_email,
                            'service'=>$av['service_name_en'],
                            'api'=>$av['api_name_en']
                        );    
                    }
                    
                }
            }

        }
        $api_name_en_array = array_unique($api_name_en_array);//去重
        $api_name_en_string = implode(',', $api_name_en_array);
        
        //读取我的api数据
        $sql = "SELECT
                    decode(
                        SUM (cnt_ret),
                        NULL,
                        0,
                        SUM (cnt_ret)
                    ) cnt_ret,
                    decode(
                        SUM (cnt_call),
                        NULL,
                        0,
                        SUM (cnt_call)
                    ) cnt_call,
                    SUM (decode(retcode, 0, 1, 0)) / COUNT (1) * 100 || '%' cnt,
                    ts.method
                FROM
                    t_statis ts
                WHERE
                    ts.username = '".$this->user_email."' and ts.method in (".$api_name_en_string.")  and retcode=0 group by method;";

        // echo $sql;die;
        $list = $this->getMonitorDataWithSql($sql);
        if(!empty($list)){
           foreach ($list as $k=>$v){
                $api_name_en = $v->method;
                if(array_key_exists($api_name_en, $api_data)){
                    $api_data[$api_name_en]['cnt'] = $v->cnt;
                    $api_data[$api_name_en]['cnt_call'] = $v->cnt_call;
                    $api_data[$api_name_en]['cnt_ret'] = $v->cnt_ret;
                }
            }
        }
        
        //读取我的api使用情况
        if(!empty($api_to_gateway_array)){
            // echo "<pre>";print_r($api_to_gateway_array);
            $cnt_result = $this->gatewaryInfo($api_to_gateway_array);
            // echo "<pre>";print_r($cnt_result);die;
            if(!empty($cnt_result)){
                foreach ($cnt_result as $cnt_key=>$cnt_val){
                    $cnt_api_name = $cnt_val['api'];
                    $api_data[$cnt_api_name]['rest_call'] = $cnt_val['cnt'];
                    $api_data[$cnt_api_name]['rest_time'] = $cnt_val['expire_time'];

                }
            }
        }

        //二维数组排序(按条用次数，返回条数，可用率，时间倒排) start
        foreach ( $api_data as $key => $row ){
             $num1[$key] = $row ['cnt_call'];
             $num2[$key] = $row ['cnt_ret'];
             $num3[$key] = $row ['cnt'];
             $num4[$key] = $row ['api_id'];
         }
        array_multisort($num1, SORT_DESC, $num2, SORT_DESC, $num3, SORT_DESC, $num4, SORT_DESC, $api_data);
        // echo "<pre>";print_r($api_data);die;
        //二维数组排序(按条用次数，返回条数，可用率，时间倒排) end

        $this->assign('head_title','我的数据－云途数据市场');
        $this->assign('data',$api_data);
        $this->display();
    }

}
